package com.rupecm.web;

import java.io.IOException;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;


@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean implements AuthenticationSuccessHandler,
		AuthenticationFailureHandler {
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	private String message = null;


	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		Set<String> roles = AuthorityUtils.authorityListToSet(authentication
				.getAuthorities());
		if (roles.contains("ROLE_GERENTE")) {

			response.sendRedirect("restritoGerente/principalGerente.jsf");
			return;
		}

		response.sendRedirect("restritoRecurso/principalRecurso.jsf");
		
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException auth)
			throws IOException, ServletException {

		response.sendRedirect("publico/login.jsf");
		message = "Erro";
		request.getSession().setAttribute("message",
				message);


	}
}